package org.mspring.platform.counter.dao;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.mspring.platform.counter.entity.Count;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.stereotype.Repository;

/**
 * 
 * @since 2014年4月25日
 * @author Gao Youbo
 */
@Repository
public class CountDaoImpl extends GenericDao<Count, Long> implements CountDao {
    @Override
    public void initTable() throws IOException {
        try (InputStream is = getClass().getResourceAsStream("/t_count.sql")) {
            String sql = IOUtils.toString(is, "UTF-8");
            getJdbcTemplate().execute(sql);
        }
    }

    @Override
    public Count findByDayAndCountKey(int day, String countKey) {
        return uniqueResult("select c from Count c where c.day = ? and c.countKey = ?", day, countKey);
    }

    @Override
    public List<Count> listByDay(int day) {
        return list("select c from Count c where c.day = ?", day);
    }

    @Override
    public Count findByCountKey(String countKey) {
        return uniqueResult("select c from Count c where c.countKey = ?", countKey);
    }

    @Override
    public long sumByCountKey(String countKey) {
        Long value = getHibernateTemplate().queryForLong("select sum(c.count) from Count c where c.countKey = ?", countKey);
        if (value != null) {
            return value.longValue();
        }
        return 0L;
    }
}
